//
//  WMRemoveWaterMarkingController.swift
//  deWaterMarkingProject
//
//  Created by admin on 2025/9/5.
//

import UIKit
import Player
import StoreKit
//import SDWebImage

class WMRemoveWaterMarkingController: WMBaseViewController {

    @IBOutlet weak var linkTxtView: UITextView!
    @IBOutlet weak var placeHolderLabel: UILabel!
    
    @IBOutlet weak var markingTopConstant: NSLayoutConstraint!
    
    @IBOutlet weak var markingTralingConstant: NSLayoutConstraint!
    //collectionView
    @IBOutlet weak var collectionView: UICollectionView!

    @IBOutlet weak var sampleView: UIView!
    @IBOutlet weak var parseView: UIView!
    
    @IBOutlet weak var segBtn1: UIButton!
    @IBOutlet weak var segBtn2: UIButton!
    @IBOutlet weak var segBtn3: UIButton!
    @IBOutlet weak var segView1: UIView!
    @IBOutlet weak var segView2: UIView!
    @IBOutlet weak var segView3: UIView!
    @IBOutlet weak var saveBtn: UIButton!
    @IBOutlet weak var rightBtn: UIButton!
    @IBOutlet weak var parseH: NSLayoutConstraint!
    @IBOutlet weak var sharedBtn: UIButton!
    
    @IBOutlet weak var textBgView: UIView!
    @IBOutlet weak var contentLabel: UILabel!
    
    @IBOutlet weak var imageBgView: UIView!
    @IBOutlet weak var imageCollect: UICollectionView!
    @IBOutlet weak var imageLeftBtn: UIButton!
    @IBOutlet weak var imageRightBtn: UIButton!
    @IBOutlet weak var imageTipsLabel: UILabel!
    
    @IBOutlet weak var videoBgView: UIView!
    @IBOutlet weak var scrollView: UIScrollView!
    
    var player: PoAVPlayer?

    var parseRecord: WMRecordModel?
    var segIndex: Int = 0
    var imgCurrentIndex: Int = 0

    var isInit = false
    var needShowAd = false
    var bannerView: BUNativeExpressBannerView?

    //TODO: ceshi
    override func viewDidLoad() {
        super.viewDidLoad()

        customNavBar.setTitle("视频解析")
        let tap = UITapGestureRecognizer(target: self, action: #selector(actionTap))
        view.addGestureRecognizer(tap)
//        self.linkTxtView.text = "0.28 猫学长这个惬意^ ⦁𖥦⦁^# 小猫 # 哈吉米哈吉米  https://v.douyin.com/q5WH8FRXMgw/ 复制此链接，打开抖音搜索，直接观看视频！ P@x.sE 12/14 wFu:/ "
        sampleView.isHidden = false
        parseView.isHidden = true
        sharedBtn.isHidden = !WXApi.isWXAppInstalled()

        collectionView.isHidden = (UserDefaults.standard.value(forKey: UserDefaultsKey.startIcon) as? String ?? "0") == "0"
        imageCollect.register(cellWithClass: UICollectionViewCell.self)
        collectionView.register(cellWithClass: UICollectionViewCell.self)
            
        Async.main(after: 10) { [weak self] in
            self?.iTunesScoreComment()
        }
        
        NotificationCenter.default.addObserver(forName: .adInitSuccessed) { [weak self] _ in
            guard let self = self else { return }
            self.isInit = true
            self.initAd()
        }

        if initAdSuccess && !isInit {
            isInit = true
            initAd()
        }

        NotificationCenter.default.addObserver(forName: .networkStatusChanged) { [weak self] _ in
            self?.collectionView.isHidden = (UserDefaults.standard.value(forKey: UserDefaultsKey.startIcon) as? String ?? "0") == "0"
            self?.collectionView.reloadData()
        }
        
        self.markingTopConstant.constant = 16 * kScreenWidth / 375.0
        self.markingTralingConstant.constant = 45 * kScreenWidth / 375.0
    }
    
    @objc func actionTap() {
        view.endEditing(true)
    }
    
    override func viewSafeAreaInsetsDidChange() {
        super.viewSafeAreaInsetsDidChange()
        
        let safeAreaInsets = view.safeAreaInsets
        scrollView.contentInset = UIEdgeInsets(
            top: safeAreaInsets.top,
            left: 0,
            bottom: safeAreaInsets.bottom,
            right: 0
        )
        scrollView.scrollIndicatorInsets = scrollView.contentInset
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        requestDynamicList()
    }

    func iTunesScoreComment() {
        let isShowStarView = UserDefaults.standard.value(forKey: UserDefaultsKey.isShowStarView) as? Int ?? 0
        if isShowStarView == 0, #available(iOS 10.3 , *) {
            SKStoreReviewController.requestReview()
            UserDefaults.standard.setValue(1, forKey: UserDefaultsKey.isShowStarView)
        }
    }

    func requestDynamicList() {
        WMAgentApi.shared.requestApi(ApiEnum.myFuncList) { res in
            let data = res["data"] as? [String: Any]
           let code: String = res["code"] as! String
            if (code == "200" || code == "0"){
                let isMember = data?["memberStatus"] as? Int == 1
                UserDefaults.standard.setValue(isMember ? 1 : 0, forKey: UserDefaultsKey.isMember)
            }
        }
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if let player = player {
            player.pause()
        }
    }

    //清除链接
    @IBAction func clearLinkBtnClickAction(_ sender: Any) {
        linkTxtView.text = ""
        placeHolderLabel.isHidden = false
        sampleView.isHidden = false
        parseView.isHidden = true
        parseRecord = nil
    }
    //解析
    @IBAction func parsingBtnClickAction(_ sender: Any) {
        view.endEditing(true)
        if !linkTxtView.text.isEmpty {
            showHUD("处理中","")
            requestParse(linkTxtView.text)
        }else{
            KBToast.show("请输入视频地址，不懂请点击下方教程")
        }
    }
    //使用教程按钮点击事件
    @IBAction func tutorialsBtnClickAction(_ sender: Any) {
        let web = WebViewController()
        web.modalPresentationStyle = .fullScreen
        web.url = UserDefaults.standard.value(forKey: UserDefaultsKey.helpUrl) as? String ?? ""
        present(web, animated: true)
    }
    //点击查看视频教程
    @IBAction func clickVideoBtnClickAction(_ sender: Any) {
        let web = WebViewController()
        web.modalPresentationStyle = .fullScreen
        web.url = UserDefaults.standard.value(forKey: UserDefaultsKey.ssysUrl) as? String ?? ""
        present(web, animated: true)
    }
    
    @IBAction func actionSeg(_ sender: UIButton) {
        let segBtns: [UIButton] = [segBtn1, segBtn2, segBtn3]
        let segViews: [UIView] = [segView1, segView2, segView3]
        for i in 0..<segBtns.count {
            let btn = segBtns[i]
            let v = segViews[i]
            btn.isSelected = btn == sender
            v.isHidden = !btn.isSelected
        }
        segIndex = ["视频", "图片", "文案"].firstIndex(of: sender.titleLabel?.text).or(0)
        let views: [UIView] = [videoBgView, imageBgView, textBgView]
        for i in 0..<views.count {
            let v = views[i]
            v.isHidden = segIndex != i
        }
        if segIndex == 1 {
            imageCollect.reloadData()
        }
        if segIndex != 0, let player = player {
            player.pause()
        }
        parseH.constant = segIndex == 2 ? 360 : 410
        saveBtn.setTitle(" \(["保存视频", "保存图片", "保存文案"][segIndex])", for: .normal)
        rightBtn.setTitle(" \(["复制视频链接", "保存全部图片", "保存文案"][segIndex])", for: .normal)
        rightBtn.setImage(UIImage(named: ["remove_copy_icon", "home_save_icon", "remove_save_icon"][segIndex]), for: .normal)
    }
    
    @IBAction func actionImageLeft(_ sender: Any) {
        if imgCurrentIndex > 0 {
            imgCurrentIndex -= 1
            imageCollect.scrollToItem(at: IndexPath(item: imgCurrentIndex, section: 0), at: .right, animated: true)
        }
    }
    
    @IBAction func actionImageRight(_ sender: Any) {
        var imgUrls: [String] = []
        if let parseRecord = parseRecord {
            if let imgs = parseRecord.imgs, !imgs.isEmpty {
                imgUrls.append(contentsOf: imgs)
            }
            if let img = parseRecord.image, !img.isEmpty, imgUrls.isEmpty {
                imgUrls.append(img)
            }
        }
        if imgCurrentIndex < imgUrls.count - 1 {
            imgCurrentIndex += 1
            imageCollect.scrollToItem(at: IndexPath(item: imgCurrentIndex, section: 0), at: .left, animated: true)
        }
    }
    
    @IBAction func actionSave(_ sender: Any) {
        let member = (UserDefaults.standard.value(forKey: UserDefaultsKey.isMember) as? Int ?? 0) == 1
        if member {
            saveOpt()
        }else {
            requestPermission { [weak self] status, msg in
                if status {
                    self?.saveOpt()
                }else {
                    Async.main {
                        self?.hideHUD()
                        self?.showTips(msg)
                        Async.main(after: 1) {
                            let vc = WMPaymentCenterController(nibName: "WMPaymentCenterController", bundle: nil)
                            self?.navigationController?.pushViewController(vc, animated: true)
                        }
                    }
                }
            }
        }
    }
    
    func saveOpt() {
        if segIndex == 0 {
            if let str = parseRecord?.videoUrl, let url = URL(string: str) {
                DownloadManager.saveVideo(url: url)
                requestEventSave(title: "保存视频", mode: "保存视频")
            }
        }else if segIndex == 1 {
            var imgUrls: [String] = []
            if let parseRecord = parseRecord {
                if let imgs = parseRecord.imgs, !imgs.isEmpty {
                    imgUrls.append(contentsOf: imgs)
                }
                if let img = parseRecord.image, !img.isEmpty, imgUrls.isEmpty {
                    imgUrls.append(img)
                }
            }
            if let url = URL(string: imgUrls[imgCurrentIndex]) {
                DownloadManager.saveImageToAlbum(url)
            }
        }else {
            UIPasteboard.general.string = contentLabel.text
            showTips("复制成功")
        }
    }
    
    @IBAction func actionCopy(_ sender: Any) {
        let member = (UserDefaults.standard.value(forKey: UserDefaultsKey.isMember) as? Int ?? 0) == 1
        if member {
            copyOpt()
        }else {
            requestPermission { [weak self] status, msg in
                if status {
                    self?.copyOpt()
                }else {
                    Async.main {
                        self?.hideHUD()
                        self?.showTips(msg)
                        Async.main(after: 1) {
                            let vc = WMPaymentCenterController(nibName: "WMPaymentCenterController", bundle: nil)
                            self?.navigationController?.pushViewController(vc, animated: true)
                        }
                    }
                }
            }
        }
    }

    func copyOpt() {
        if segIndex == 0 {
            UIPasteboard.general.string = parseRecord?.videoUrl ?? ""
            showTips("复制成功")
            requestEventSave(title: "复制视频链接", mode: "复制视频链接")
        }else if segIndex == 1 {
            var imgUrls: [String] = []
            if let parseRecord = parseRecord {
                if let imgs = parseRecord.imgs, !imgs.isEmpty {
                    imgUrls.append(contentsOf: imgs)
                }
                if let img = parseRecord.image, !img.isEmpty, imgUrls.isEmpty {
                    imgUrls.append(img)
                }
            }
            if !imgUrls.isEmpty {
                showHUD("处理中")
            }
            for i in 0..<imgUrls.count {
                if let url = URL(string: imgUrls[i]) {
                    DownloadManager.saveImageToAlbum(url, showTips: i==imgUrls.count-1)
                }
            }
            requestEventSave(title: "点击去水印下载", mode: "点击去水印下载")
        }else {
            UIPasteboard.general.string = contentLabel.text
            showTips("复制成功")
        }
    }
    
    @IBAction func actionShare(_ sender: Any) {
        if !WXApi.isWXAppInstalled() {
            showTips("暂无可分享的平台")
            return
        }
        let member = (UserDefaults.standard.value(forKey: UserDefaultsKey.isMember) as? Int ?? 0) == 1
        if member {
            shareOpt()
        }else {
            requestPermission { [weak self] status, msg in
                if status {
                    self?.shareOpt()
                }else {
                    Async.main {
                        self?.hideHUD()
                        self?.showTips(msg)
                        Async.main(after: 1) {
                            let vc = WMPaymentCenterController(nibName: "WMPaymentCenterController", bundle: nil)
                            self?.navigationController?.pushViewController(vc, animated: true)
                        }
                    }
                }
            }
        }
        requestEventSave(title: "分享视频", mode: "分享视频")
    }
    
    func shareOpt() {
        if segIndex == 0 {
            if let parseRecord = parseRecord, let url = parseRecord.videoUrl {
                let shareView = ShareView(frame: UIScreen.main.bounds)
                shareView.shareItemBlock = { index in
                    let req = SendMessageToWXReq()
                    let message = WXMediaMessage()
                    let img = WXVideoObject()
                    img.videoUrl = url
                    message.mediaObject = img
                    req.message = message
                    req.scene = Int32(index)
                    WXApi.send(req)
                }
                UIApplication.shared.delegate?.window??.addSubview(shareView)
            }
        }else if segIndex == 1 {
            var imgUrls: [String] = []
            if let parseRecord = parseRecord {
                if let imgs = parseRecord.imgs, !imgs.isEmpty {
                    imgUrls.append(contentsOf: imgs)
                }
                if let img = parseRecord.image, !img.isEmpty, imgUrls.isEmpty {
                    imgUrls.append(img)
                }
            }
            if let url = URL(string: imgUrls[imgCurrentIndex]) {
                showHUD("处理中")
                let task = URLSession.shared.dataTask(with: url) { [weak self] (data, response, error) in
                    Async.main {
                        self?.hideHUD()
                    }
                    if let data = data {
                        Async.main {
                            let shareView = ShareView(frame: UIScreen.main.bounds)
                            shareView.shareItemBlock = { index in
                                let req = SendMessageToWXReq()
                                let message = WXMediaMessage()
                                let img = WXImageObject()
                                img.imageData = data
                                message.mediaObject = img
                                req.message = message
                                req.scene = Int32(index)
                                WXApi.send(req)
                            }
                            UIApplication.shared.delegate?.window??.addSubview(shareView)
                        }
                    }
                }
                task.resume()
            }
        }else {
            let shareView = ShareView(frame: UIScreen.main.bounds)
            shareView.shareItemBlock = { [weak self] index in
                let req = SendMessageToWXReq()
                req.bText = true
                req.text = self?.contentLabel.text ?? ""
                req.scene = Int32(index)
                WXApi.send(req)
            }
            UIApplication.shared.delegate?.window??.addSubview(shareView)
        }
    }
    
    func requestParse(_ text: String) {
        WMAgentApi.shared.requestApi(ApiEnum.parseVideo(text)) { res in
            let code: String = res["code"] as! String
            Async.main { [weak self] in
                self?.hideHUD()
                if !(code == "200" || code == "0") {
                    let message = res["message"]
                    KBToast.show(message as? String ?? "")
                    if(code == "-1"){ //停留2秒跳转到付费页面
                        Async.main(after: 2) {
                            let vc = WMPaymentCenterController(nibName: "WMPaymentCenterController", bundle: nil)
                            self?.navigationController?.pushViewController(vc, animated: true)
                        }
                    }
                }
            }
            
            if  (code == "200" || code == "0"), let dict = res["data"] as? [String: Any] {
                let data = WMRecordModel()
                data.title = dict["title"] as? String
                data.image = dict["image"] as? String
                data.videoUrl = dict["videoUrl"] as? String
                data.imgs = dict["imgs"] as? [String]
                data.orgUrl = text
                let formatter = DateFormatter()
                formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
                data.recordId = formatter.string(from: Date())
                data.imgsStr = data.imgs.or([]).joined(separator: "-[]-")
                self.parseRecord = data
                Async.main {
                    self.sampleView.isHidden = true
                    self.parseView.isHidden = false
                    self.contentLabel.text = data.title.or("")
                    self.imgCurrentIndex = 0
                    var imgUrls: [String] = []
                    if let parseRecord = self.parseRecord {
                        if let imgs = parseRecord.imgs, !imgs.isEmpty {
                            imgUrls.append(contentsOf: imgs)
                        }
                        if let img = parseRecord.image, !img.isEmpty, imgUrls.isEmpty {
                            imgUrls.append(img)
                        }
                    }
                    if(imgUrls.count == 0){
                        self.imageLeftBtn.isHidden = true
                        self.imageRightBtn.isHidden = true
                        self.imageTipsLabel.isHidden = false
                    }else{
                        self.imageLeftBtn.isHidden = false
                        self.imageRightBtn.isHidden = false
                        self.imageTipsLabel.isHidden = true
                    }
                    
                    self.imageCollect.reloadData()
                    self.videoBgView.subviews.forEach({ $0.removeFromSuperview() })
                    self.videoBgView.backgroundColor = .black
                    if let videoUrl = data.videoUrl, !videoUrl.isEmpty {
                        self.actionSeg(self.segBtn1)
                        if let url = URL(string: videoUrl) {
                            self.videoBgView.addSubview(self.videoPlayer)
                            PoAVPlayerCacheManager.shared.deleteAllFiles()
                            // avplayer是显示层
                            let player = PoAVPlayer(frame: self.videoBgView.bounds)
                            player.autoresizingMask = [.flexibleWidth, .flexibleHeight]
                            // controlView是播放的交互控制层，可自定义
                            let control = PoAVPlayerControlView(player: player)
                            player.addControlLayer(control)
                            self.videoBgView.addSubview(player)
                            player.play(with: url, needCache: false)
                            self.player = player
                        }
                    }else {
                        self.player = nil
                        if let imgUrl = data.image, !imgUrl.isEmpty {
                            self.actionSeg(self.segBtn2)
                        }else {
                            self.actionSeg(self.segBtn3)
                        }
                        
                        let label = UILabel()
                        label.text = "无视频"
                        label.textColor = .white
                        label.font = UIFont.systemFont(ofSize: 16, weight: .medium)
                        self.videoBgView.addSubview(label)
                        label.snp.makeConstraints { make in
                            make.center.equalToSuperview()
                        }
                    }
                }
                AppDatabase.shared.insertRecord(data)
            }
        }
       
    }
    
    func requestPermission(_ complation: @escaping (Bool, String)->Void) {
        WMAgentApi.shared.requestApi(ApiEnum.permission) { res in
            let code: String = res["code"] as! String
            let message: String? = res["message"] as? String
            complation((code == "200" || code == "0"), message.or(""))
        }
    }
    
    @objc func actionJC() {
        view.endEditing(true)
        let web = WebViewController()
        web.modalPresentationStyle = .fullScreen
        web.url = UserDefaults.standard.value(forKey: UserDefaultsKey.ssysUrl) as? String ?? ""
        present(web, animated: true)
    }
    
    lazy var videoPlayer: VideoPlayerView = {
        let player = VideoPlayerView(frame: videoBgView.bounds)
        
        return player
    }()
    
}

extension WMRemoveWaterMarkingController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        var imgUrls: [String] = []
        if let parseRecord = parseRecord {
            if let imgs = parseRecord.imgs, !imgs.isEmpty {
                imgUrls.append(contentsOf: imgs)
            }
            if let img = parseRecord.image, !img.isEmpty, imgUrls.isEmpty {
                imgUrls.append(img)
            }
        }
        return collectionView == imageCollect ? imgUrls.count : (12 + (needShowAd ? 1 : 0))
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if collectionView == imageCollect {
            let cell = collectionView.dequeueReusableCell(withClass: UICollectionViewCell.self, for: indexPath)
            cell.contentView.subviews.forEach({ $0.removeFromSuperview() })

            var imgUrls: [String] = []
            if let parseRecord = parseRecord {
                if let imgs = parseRecord.imgs, !imgs.isEmpty {
                    imgUrls.append(contentsOf: imgs)
                }
                if let img = parseRecord.image, !img.isEmpty, imgUrls.isEmpty {
                    imgUrls.append(img)
                }
            }
            let iv = UIImageView()
            iv.sd_setImage(with: URL(string: imgUrls[indexPath.item])) { img, err, _, _ in
                if let img = img, let data = img.pngData() {
                    UserDefaults.standard.setValue(data, forKey: imgUrls.first.or(""))
                    UserDefaults.standard.synchronize()
                }
            }
//            iv.sd_setImage(with: imgUrls[indexPath.item])
//            iv.setImageUrl(imgUrls[indexPath.item], complateHandler: { img, _ in
//                if let img = img, let data = img.pngData() {
//                    UserDefaults.standard.setValue(data, forKey: imgUrls.first.or(""))
//                    UserDefaults.standard.synchronize()
//                }
//            })
            iv.contentMode = .scaleAspectFill
            iv.clipsToBounds = true
            cell.contentView.addSubview(iv)
            iv.snp.makeConstraints { make in
                make.top.left.right.bottom.equalToSuperview()
            }

            return cell
        }
        let cell = collectionView.dequeueReusableCell(withClass: UICollectionViewCell.self, for: indexPath)
        cell.contentView.subviews.forEach({ $0.removeFromSuperview() })

        if indexPath.item < 12 {
            let iv = UIImageView()
            cell.contentView.addSubview(iv)
            iv.snp.makeConstraints { make in
                make.top.left.right.bottom.equalToSuperview()
            }
//            iv.isUserInteractionEnabled = true
//            let tap = UITapGestureRecognizer(target: self, action: #selector(actionJC))
//            iv.addGestureRecognizer(tap)
        }else {
            cell.contentView.addSubview(bannerView!)
        }

        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return collectionView == imageCollect ? 0 : 20
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return collectionView == imageCollect ? 0 : (kScreenWidth - 64 - 52 * 4) / 3 - 1
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return collectionView == imageCollect ? CGSize(width: kScreenWidth, height: 295) : (indexPath.item < 12 ? CGSize(width: 52, height: 12) : CGSize(width: kScreenWidth, height: 210))
    }
            
}

extension WMRemoveWaterMarkingController: UITextViewDelegate {
    
    func textViewDidChange(_ textView: UITextView) {
        placeHolderLabel.isHidden = !textView.text.isEmpty
    }
    
}

extension WMRemoveWaterMarkingController: BUNativeExpressBannerViewDelegate {
    
    func initAd() {
        if !isInit { return }
        bannerView = BUNativeExpressBannerView(slotID: "970745838", rootViewController: self, adSize: CGSize(width: 300, height: 200))
        bannerView!.frame = CGRect(x: (kScreenWidth - 300 - 64) / 2, y: 0, width: 300, height: 200)
        bannerView!.delegate = self
        bannerView!.loadAdData()
    }
    
    func nativeExpressBannerAdViewDidLoad(_ bannerAdView: BUNativeExpressBannerView) {
        let isMember = UserDefaults.standard.value(forKey: UserDefaultsKey.isMember) as? Int ?? 0
        let showAd = UserDefaults.standard.value(forKey: UserDefaultsKey.showad) as? Int ?? 1
        if isMember == 1 || showAd == 0 {
            needShowAd = false
        }else {
            needShowAd = true
        }
        collectionView.reloadData()
    }
    
    func nativeExpressBannerAdViewDidRemoved(_ bannerAdView: BUNativeExpressBannerView) {
        needShowAd = false
        collectionView.reloadData()
    }
    
    func nativeExpressBannerAdView(_ bannerAdView: BUNativeExpressBannerView, didLoadFailWithError error: Error?) {
        
    }

}
